package org.zn.mvcbase.servlet;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
* 
* @Company OBOR
* @Author 周楠
* @Description
* 2019年6月21日
*
*/
public class ParameterRequestWrapper extends HttpServletRequestWrapper {
		 
		private Map<String, String[]> params = new HashMap<String, String[]>();
	 
		public ParameterRequestWrapper(HttpServletRequest request) {
			// 将request交给父类，以便于调用对应方法的时候，将其输出，其实父亲类的实现方式和第一种new的方式类似
			super(request);
			// 将参数表，赋予给当前的Map以便于持有request中的参数
			this.params.putAll(request.getParameterMap());
		}
	 
		public ParameterRequestWrapper(HttpServletRequest request, Map<String, Object> extendParams) {
			this(request);
			addAllParameters(extendParams);
		}
	 
		@Override
		public String getParameter(String name) {
			String[] values = params.get(name);
			if (values == null || values.length == 0) {
				return null;
			}
			return values[0];
		}
				
		
		@Override
		public Map<String, String[]> getParameterMap() {
		// TODO Auto-generated method stub
		return params;
		}
		
			
		@Override
		public Enumeration<String> getParameterNames() {
		// TODO Auto-generated method stub
			
			Set<String> paramNames = params.keySet();
			
			return Collections.enumeration(paramNames);
			 
		}
		
	
		
		
	 
		@Override
		public String[] getParameterValues(String name) {
			return params.get(name);
		}
	 
		public void addAllParameters(Map<String, Object> otherParams) {
			for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
				addParameter(entry.getKey(), entry.getValue());
			}
		}
	 
		public void addParameter(String name, Object value) {
			if (value != null) {
				if (value instanceof String[]) {
					params.put(name, (String[]) value);
				} else if (value instanceof String) {
					params.put(name, new String[] { (String) value });
				} else {
					params.put(name, new String[] { String.valueOf(value) });
				}
			}
		}

	

}
